//
//  TcpManager.m
//  socketDemo
//
//  Created by 吳瀾洲 on 2020/8/7.
//  Copyright © 2020 kingboyrang. All rights reserved.
//

#import "TcpClient.h"

@interface TcpClient ()

@end

@implementation TcpClient



+ (TcpClient *)shareInstance{
    
    static TcpClient *notificationManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        notificationManager = [[TcpClient alloc] init];
    });
    return notificationManager;
}

- (instancetype)init{
    if (self=[super init]) {
        tcpConnector = [[TcpConnector alloc] init];
    }
    return self;
}

- (TcpConnector *)getConnector{
    return tcpConnector;
}
//连接
- (void)connectToHost:(NSString *)host port:(uint16_t)port{
    
    if (tcpConnector.socket == nil) {
        tcpConnector.socket =  [[GCDAsyncSocket alloc] initWithDelegate:tcpConnector delegateQueue:dispatch_get_global_queue(0, 0)];
    }
    
    if (![tcpConnector.socket isConnected]) {
        NSError *error = nil;
        [tcpConnector.socket connectToHost:host onPort:port withTimeout:-1 error:&error];
        
       if (error)
       {
           //连接失败
           if (tcpConnector.connectStateChangedBlock) {
               tcpConnector.connectStateChangedBlock(TcpConnectFailed);
           }
           NSLog(@"connectToHost error %@",error);
           [tcpConnector.socket disconnect];
       }
        
    }
}
//断开
- (void)disconnect{
    if ([tcpConnector.socket isConnected]) {
        [tcpConnector.socket disconnect];
    }
    
}

@end
